/*
 * Copyright (c) 2015 qunar. All Rights Reserved.
 */
package com.guoyu.project.common.spring;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

/**
 * spring上下文操作工具类
 * 
 * @author: libo Date: 15-1-14 Time: 下午1:31
 * @version: \$Id$
 */
@Service
public class ApplicationContextSupport implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * 根据class获取对象
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getBean(Class<T> clazz) {
        try {
            return applicationContext.getBean(clazz);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据class从容器获取对应对象
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> getBeans(Class<T> clazz) {
        Map<String, T> maps = null;
        try {
            maps = applicationContext.getBeansOfType(clazz);
        } catch (Exception e) {
        }

        if (MapUtils.isEmpty(maps)) {
            return null;
        }

        List<T> list = Lists.newArrayList();
        list.addAll(maps.values());
        return list;
    }

    /**
     * 根据名称获取对象
     *
     * @param beanName
     * @param <T>
     * @return
     */
    public <T> T getBean(String beanName) {
        try {
            return (T) applicationContext.getBean(beanName);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据名称获取对象
     *
     * @param beanName
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getBean(String beanName, Class<T> clazz) {
        try {
            return applicationContext.getBean(beanName, clazz);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
